package com.itheima.reggie.controller;


import com.itheima.reggie.common.R;
import org.apache.poi.util.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

@RestController
@RequestMapping("/common")
public class CommonController {

    @Value("${reggie.path}")
    private String baseDir;

    //springmvc文件上传要求
    //要求1:必须使用MultipartFil类型接收上传文件对象
    //要求2:MultipartFil类型参数名字必须与前端文件域表单元素name属性值一样,如果不一样需要使用@PequestParm("别名")
    @RequestMapping("/upload")
    public R<String> upload(MultipartFile file) throws IOException {

        //1.获取上传文件的文件名
        String fileName = file.getOriginalFilename();

        //2.讲文件保存到d:\img目录下
        File dir = new File(baseDir);
        if (!dir.exists()) {
            dir.mkdir(); //这里使用前提必须有d盘,这里判断如果img目录没有就创建
        }

        //进行保存
        file.transferTo(new File(baseDir + fileName)); //d:\img\abc,jpg

        //返回值
        return R.success(fileName);
    }

    @RequestMapping("/download")
    public void download(@RequestParam("name") String fileName, HttpServletResponse response) throws IOException {

        //输入流
        FileInputStream inputStream = new FileInputStream(baseDir + fileName);

        //输出流
        ServletOutputStream outputStream = response.getOutputStream();


        //讲输入流输出给输出流
        IOUtils.copy(inputStream, outputStream);
    }

}
